package com.iwhalecloud.bss.kite.cucc.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.util.KiteTransactionUtils;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author lyx
 * @version V1.0
 * @Description:
 * @date 2021/11/5
 * @Package com.iwhalecloud.bss.kite.cucc.web.interceptor
 */
public class UpdateAttrInterceptor extends HandlerInterceptorAdapter {

    private static final ZLogger LOGGER = ZLoggerFactory.getLogger(UpdateAttrInterceptor.class, KeyConsts.LOG_MODULE);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws UnsupportedEncodingException {
        LOGGER.info("UpdateAttrInterceptor");
        String url=request.getRequestURL().toString();
        // 如果请求路径包含取消字符，则不保存
        if (KiteStringUtils.isNotEmpty(url) && KiteStringUtils.contains(url, "cancle")) {
            return true;
        }
        String updateAttrs = request.getHeader("updateAttrs");
        if (KiteStringUtils.isBlank(updateAttrs)) {
            return true;
        }
        JSONObject updateAttr = JSONObject.parseObject(URLDecoder.decode(updateAttrs, "UTF-8"));
        String sceneInstId = KiteMapUtils.getString(updateAttr, "sceneInstId");
        if (KiteStringUtils.isBlank(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        String custId = KiteMapUtils.getString(updateAttr, "custId");
        List<Map<String, Object>> kiteInsts = KiteMapUtils.getValue(updateAttr, "kiteInsts");
        if (Objects.isNull(kiteInsts) || kiteInsts.isEmpty()) {
            return true;
        }
        if (KiteStringUtils.isEmpty(KiteTransactionUtils.getTransactionId())) {
            KiteTransactionUtils.beginTransaction();
        }
        String finalSceneInstId = sceneInstId;
        kiteInsts.forEach(kiteInst -> {
            String instId = KiteMapUtils.getString(kiteInst, "instId");
            String instTypeName = KiteMapUtils.getString(kiteInst, "instType");
            List<Map<String, Object>> kiteAttrList = KiteMapUtils.getValue(kiteInst, "attrs");
            IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
            if (Objects.isNull(kiteAttrList) || kiteAttrList.isEmpty()) {
                return;
            }
            // 默认是产品属性
            InstType instType = InstType.PROD_INST;
            if (KiteStringUtils.equals(instTypeName, "PROD_INST_FUNC")) {
                instType = InstType.PROD_INST_FUNC;
            }
            else if (KiteStringUtils.equals(instTypeName, "ADDITIONAL_OFFER_INST")) {
                instType = InstType.ADDITIONAL_OFFER_INST;
            }
            InstType finalInstType = instType;
            kiteAttrList.forEach(kiteAttr -> operateSceneInstService
                .setAttrValue(finalSceneInstId, finalInstType, instId, KiteMapUtils.getString(kiteAttr, "fieldName"),
                    KiteMapUtils.getString(kiteAttr, "value"), KiteMapUtils.getString(kiteAttr, "valueDesc")));
        });
        // 这里需要提交缓存事务，否则会丢失
        KiteTransactionUtils.commit();
        return true;
    }
}
